package com.rookie.im.learn.io.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@Configurable
public class TopicRabbitConfig implements BeanPostProcessor {

    @Bean
    public Queue topicExchangeQueueA() {
        return new Queue(RabbitMQConfig.RABBITMQ_DEMO_TOPIC_EXCHANGE_QUEUE_A, true, false, false);
    }
    @Bean
    public Queue topicExchangeQueueB() {
        return new Queue(RabbitMQConfig.RABBITMQ_DEMO_TOPIC_EXCHANGE_QUEUE_B, true, false, false);
    }
    @Bean
    public Queue topicExchangeQueueC() {
        return new Queue(RabbitMQConfig.RABBITMQ_DEMO_TOPIC_EXCHANGE_QUEUE_C, true, false, false);
    }

    @Bean
    public TopicExchange rabbitmqDemoTopicExchange() {
        return new TopicExchange(RabbitMQConfig.RABBITMQ_DEMO_TOPIC_EXCHANGE_NAME,true, false);
    }

    @Bean
    public Binding bindTopicA() {
        //队列C绑定到TopicExchange交换机
        return BindingBuilder.bind(topicExchangeQueueA()).to(rabbitmqDemoTopicExchange()).with("a.*");
    }
    @Bean
    public Binding bindTopicB() {
        //队列B绑定到TopicExchange交换机
        return BindingBuilder.bind(topicExchangeQueueB()).to(rabbitmqDemoTopicExchange()).with("b.*");
    }
    @Bean
    public Binding bindTopicC() {
        //队列C绑定到TopicExchange交换机
        return BindingBuilder.bind(topicExchangeQueueC()).to(rabbitmqDemoTopicExchange()).with("rabbit.#");
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RabbitAdmin) {
            RabbitAdmin rabbitAdmin = (RabbitAdmin) bean;
            rabbitAdmin.declareExchange(rabbitmqDemoTopicExchange());
            rabbitAdmin.declareBinding(bindTopicA());
            rabbitAdmin.declareBinding(bindTopicB());
            rabbitAdmin.declareBinding(bindTopicC());
        }
        return bean;
    }

}
